package com.lxw.report.meta.utils;

import com.lxw.report.meta.entity.DataBase;
import com.lxw.report.meta.query.dbpool.DataSourcePoolFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Jdbc工具类.
 *
 * @author lxw
 */
public class JdbcUtil {
    private static final Logger logger = LoggerFactory.getLogger(JdbcUtil.class);
    private static final Map<String, DataSource> dataSourceMap = new ConcurrentHashMap<>(100);

    //从数据源连接池集合中获取连接，如果没有连接池  那么重新创建一个
    public static DataSource getDataSource(DataBase dataBase) {
        //用数据源用户名,密码,jdbcUrl做为key
        final String key = String.format("%s|%s", dataBase.getUser(),dataBase.getJdbcUrl())
            .toLowerCase();
        DataSource dataSource = dataSourceMap.get(key);
        if (dataSource == null) {
//            dataSource = DataSourcePoolFactory.create(dataBase.getPoolType()).wrap(dataBase);
            dataSourceMap.put(key, dataSource);
        }
        return dataSource;
    }

    //对数据源进行修改操作时，重新创建该数据源对应的连接池
    public static void freshDataSourcePool(DataBase dataBase) {
        //用数据源用户名,密码,jdbcUrl做为key
        final String key = String.format("%s|%s", dataBase.getUser(),dataBase.getJdbcUrl())
                .toLowerCase();
//        DataSource dataSource = DataSourcePoolFactory.create(dataBase.getPoolType()).wrap(dataBase);
//        dataSourceMap.put(key, dataSource);
        dataSourceMap.put(key, null);
    }

    public static void releaseJdbcResource(final Connection conn, final Statement stmt, final ResultSet rs) {
        try {
            if (stmt != null) {
                stmt.close();
            }
            if (rs != null) {
                rs.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (final SQLException ex) {
            logger.error("数据库资源释放异常", ex);
            throw new RuntimeException("数据库资源释放异常", ex);
        }
    }
}
